"""
什么是迭代器和可迭代对象
"""

from collections.abc import Iterable, Iterator


def use_iterable_iterator():
    user_list = ["Kevin"]
    user_iterator = iter(user_list)
    print(isinstance(user_iterator, Iterable))
    print(isinstance(user_iterator, Iterator))
    # 输出结果：
    """
    True
    True
    """


class Company(object):
    def __init__(self, employee_list):
        self.employee_list = employee_list

    def __getitem__(self, item):
        return self.employee_list[item]


def use_company():
    company = Company(["Kevin", "葛小伦"])
    for item in company:
        print(item)
    # 输出结果：
    """
    Kevin
    葛小伦
    """


class MyIterator(Iterator):
    """
    自定义迭代器
    """

    def __init__(self, iter_list):
        self.iter_list = iter_list
        self.index = 0

    def __next__(self):
        """
        真正返回迭代值的逻辑
        """
        try:
            item = self.iter_list[self.index]
        except IndexError as e:
            raise StopIteration
        self.index += 1
        return item


class School(object):
    def __init__(self, students):
        self.students = students

    def __iter__(self):
        return MyIterator(self.students)


def use_student():
    school = School(["Kevin", "葛小伦"])
    iterator = iter(school)
    while True:
        try:
            print(next(iterator))
        except StopIteration:
            break
    # 输出结果：
    """
    Kevin
    葛小伦
    """


if __name__ == '__main__':
    use_iterable_iterator()
    use_company()
    use_student()
